package com.example.mydy;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.mydy.model.UserInfo;
import com.example.mydy.model.WithdrawalRequest;
import com.example.mydy.utils.MockDataManager;
import com.example.mydy.utils.WithdrawalService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class WithdrawalActivity extends AppCompatActivity {

    private static final String TAG = "WithdrawalActivity";

    private TextView userBalanceText;
    private EditText withdrawalAmountEdit;
    private EditText accountNameEdit;
    private EditText accountNumberEdit;
    private Button withdrawButton;
    private Button viewHistoryButton;
    private ImageButton backButton;

    private MockDataManager mockDataManager;
    private WithdrawalService withdrawalService;
    private UserInfo currentUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_withdrawal);

        // 初始化服务
        mockDataManager = MockDataManager.getInstance();
        withdrawalService = WithdrawalService.getInstance(this);
        
        // 获取当前用户
        currentUser = mockDataManager.getCurrentUser();
        if (currentUser == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化视图
        initViews();
        setupListeners();
        
        // 显示用户余额
        updateBalanceDisplay();
    }

    private void initViews() {
        userBalanceText = findViewById(R.id.user_balance);
        withdrawalAmountEdit = findViewById(R.id.withdrawal_amount);
        accountNameEdit = findViewById(R.id.account_name);
        accountNumberEdit = findViewById(R.id.account_number);
        withdrawButton = findViewById(R.id.btn_withdraw);
        viewHistoryButton = findViewById(R.id.btn_view_history);
        backButton = findViewById(R.id.btn_back);
    }

    private void setupListeners() {
        backButton.setOnClickListener(v -> finish());
        
        withdrawButton.setOnClickListener(v -> {
            if (validateInput()) {
                showConfirmDialog();
            }
        });
        
        viewHistoryButton.setOnClickListener(v -> {
            Intent intent = new Intent(WithdrawalActivity.this, WithdrawalManagementActivity.class);
            startActivity(intent);
        });
    }
    
    private void updateBalanceDisplay() {
        if (currentUser != null) {
            userBalanceText.setText(String.format("¥ %.2f", Double.parseDouble(currentUser.getBalance())));
        }
    }

    private boolean validateInput() {
        String amountText = withdrawalAmountEdit.getText().toString().trim();
        String accountName = accountNameEdit.getText().toString().trim();
        String accountNumber = accountNumberEdit.getText().toString().trim();
        
        // 验证提现金额
        if (TextUtils.isEmpty(amountText)) {
            withdrawalAmountEdit.setError("请输入提现金额");
            return false;
        }
        
        double amount;
        try {
            amount = Double.parseDouble(amountText);
            if (amount <= 0) {
                withdrawalAmountEdit.setError("提现金额必须大于0");
                return false;
            }
        } catch (NumberFormatException e) {
            withdrawalAmountEdit.setError("请输入有效数字");
            return false;
        }
        
        // 验证余额是否足够
        double balance = Double.parseDouble(currentUser.getBalance());
        if (amount > balance) {
            withdrawalAmountEdit.setError("提现金额不能大于账户余额");
            return false;
        }
        
        // 验证账户名
        if (TextUtils.isEmpty(accountName)) {
            accountNameEdit.setError("请输入收款账户名");
            return false;
        }
        
        // 验证账号
        if (TextUtils.isEmpty(accountNumber)) {
            accountNumberEdit.setError("请输入收款账号");
            return false;
        }
        
        return true;
    }

    private void showConfirmDialog() {
        double amount = Double.parseDouble(withdrawalAmountEdit.getText().toString().trim());
        String accountName = accountNameEdit.getText().toString().trim();
        String accountNumber = accountNumberEdit.getText().toString().trim();
        
        new AlertDialog.Builder(this)
                .setTitle("确认提现")
                .setMessage(String.format("您确定要提现 ¥%.2f 到以下账户吗？\n\n收款人: %s\n账号: %s", 
                        amount, accountName, accountNumber))
                .setPositiveButton("确认", (dialog, which) -> {
                    submitWithdrawal(amount, accountName, accountNumber);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void submitWithdrawal(double amount, String accountName, String accountNumber) {
        if (currentUser == null) {
            Toast.makeText(this, "用户信息不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 创建提现请求
        WithdrawalRequest request = new WithdrawalRequest();
        request.setUserId(currentUser.getId());
        request.setUsername(currentUser.getUsername());
        request.setUserNickname(currentUser.getNickname());
        request.setAmount(amount);
        request.setRealName(accountName);
        request.setAlipayAccount(accountNumber);
        request.setStatus(WithdrawalRequest.STATUS_PENDING);
        
        // 提交提现请求
        withdrawalService.requestWithdrawal(request, new WithdrawalService.WithdrawalCallback() {
            @Override
            public void onSuccess() {
                // 更新UI必须在主线程
                runOnUiThread(() -> {
                    // 显示成功提示
                    showSuccessDialog();
                    
                    // 清空输入框
                    withdrawalAmountEdit.setText("");
                    accountNameEdit.setText("");
                    accountNumberEdit.setText("");
                });
            }
            
            @Override
            public void onFailure(String errorMessage) {
                runOnUiThread(() -> {
                    Toast.makeText(WithdrawalActivity.this, "提现申请失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                });
            }
        });
    }

    private void showSuccessDialog() {
        new AlertDialog.Builder(this)
                .setTitle("申请已提交")
                .setMessage("您的提现申请已成功提交，请等待审核。您可以在提现记录中查看进度。")
                .setPositiveButton("查看记录", (dialog, which) -> {
                    Intent intent = new Intent(WithdrawalActivity.this, WithdrawalManagementActivity.class);
                    startActivity(intent);
                    finish();
                })
                .setNegativeButton("返回", (dialog, which) -> finish())
                .setCancelable(false)
                .show();
    }
} 